<?php

namespace app\common\model;

use think\Db;
use think\Model;

class Activities extends Model
{
    /**
     * 数据完成
     * @var array
     */
    protected $auto = [];
    protected $insert = ['status' => 1, 'has_num' => 0, 'create_time', 'update_time'];
    protected $update = ['update_time'];

    protected function setCreateTimeAttr()
    {
        return time();
    }

    protected function setUpdateTimeAttr()
    {
        return time();
    }

    protected function getStartTimeAttr($value)
    {
        return date('Y-m-d', $value);
    }

    protected function getEndTimeAttr($value)
    {
        return date('Y-m-d', $value);
    }

    protected function setStartTimeAttr($value)
    {
        return strtotime($value);
    }

    protected function setEndTimeAttr($value)
    {
        return strtotime($value);
    }

    /**
     * Notes:判断当前是否存在可以获得奖励的活动
     * User: Administrator
     * Date: 2023/9/4
     * Time: 16:57
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function isExistActivity()
    {
        $where = [
            'start_time' => ['<=', time()],
            'end_time' => ['>', time()],
            'status' => 1,
        ];
        $id = self::where($where)->value('id');
        if ($id > 0) {
            return $id;
        } else {
            return 0;
        }
    }

    /**
     * Notes:添加次数
     * User: Administrator
     * Date: 2023/9/4
     * Time: 17:08
     * @param $id
     * @throws \think\exception\DbException
     */
    public static function incNum($id)
    {
        $row = self::get($id);
        $row->has_num += 1;
        if ($row->total_num <= $row->has_num) {
            $row->status = 2;
        }

        $row->save();
    }

    public function members()
    {
        $this->hasMany('ActivityMembers', 'id', 'activity_id');
    }
}